package com.yc.blog.web;

import com.yc.blog.util.Utils;
import com.yc.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;

@RestController
@Slf4j
public class IndexDo {

    @RequestMapping("hello/{name}")
    Mono<Result> hello(@PathVariable String name) {
        return Mono.just("Hello " + name)
                .map(Result::ok);
    }

    String uploadDir = "F:\\上课视频\\143\\0402\\";

    @PostMapping("upload")
    Mono<Result> upload(ServerWebExchange exchange) {
        List<Map<String, String>> files = new ArrayList<>();
        return exchange.getSession()
                .then(exchange.getMultipartData())
                .doOnNext(mvm -> {
                    mvm.forEach((name, parts) -> {
                        parts.forEach(part -> {
                            // 提取文件名
                            List<String> disposition = part.headers().get("Content-Disposition");
                            String value = disposition.get(0);
                            String fname = value.replaceAll(".+filename=\"([^\"]*)\"", "$1");
                            if (fname.isEmpty()) return;
                            // 构建结果对象
                            Map<String, String> map = new HashMap<>();
                            map.put("oldName", fname);
                            // 构建随机文件名
                            String filename = UUID.randomUUID().toString();
                            if (fname.contains(".")) {
                                String suffix = fname.substring(fname.lastIndexOf("."));
                                filename += suffix;
                            }
                            String filepath = uploadDir + filename;
                            log.debug("存储上传文件：%s => %s".formatted(fname,filepath));
//                            part.content().subscribe(dataBuffer -> {
//                                Utils.saveFile(dataBuffer, filepath, true);
//                            });
                            Utils.saveFile(part.content(), filepath, false);
                            map.put("newName", filename);
                            files.add(map);
                        });
                    });
                }).thenReturn(Result.ok("文件上传成功!", files));
    }

}
